package pl.un4giv3n.mightvsmagic.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class AutocompleteEmailAction extends PersistenceAction {
	private static final long serialVersionUID = 1L;
	private String email;
	private Map<String, String> json;

	public String execute() {
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String getEmails() {
		json = new HashMap<String, String>();

		if (email != null && email.length() > 2) {
			EntityManager entityManager = getEntityManager();
			Query nativeQuery = entityManager.createNativeQuery("select email from User where login like :email");
			nativeQuery.setParameter("email", email+"%");
			List<String> emails = nativeQuery.getResultList();
			for (String mail : emails) {
				json.put(mail, mail);
			}
			entityManager.close();
		}

		return SUCCESS;
	}

	public Map<String, String> getJson() {
		return json;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getEmail() {
		return email;
	}
}
